<template>
<div class="app-container">
  <!-- 面包屑导航 -->
  <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 20px;">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>相册管理</el-breadcrumb-item>
    <el-breadcrumb-item>相册列表</el-breadcrumb-item>
  </el-breadcrumb>
  <el-card class="main-card">
    <!-- 标题 -->
    <div class="operation-container">
      <el-input v-model="query.name" prefix-icon="el-icon-search" size="small" placeholder="请输入相册名" style="width:200px" @keyup.enter.native="searchAlbums"/>
      <el-button type="primary" size="small" icon="el-icon-search"  @click="searchAlbums">
        搜索
      </el-button>
      <el-button icon="el-icon-refresh" size="small" @click="reload">重置</el-button>
      <el-button type="primary" size="small" icon="el-icon-plus" @click="openModel(null)">
        新建相册
      </el-button>
    </div>
    <!-- 相册列表 -->
    <el-row class="album-container" :gutter="12">
      <!-- 空状态 -->
      <el-empty v-if="albumList == null" description="暂无相册" />
      <el-col v-else v-for="item of albumList" :key="item.id" :md="6">
        <div class="album-item" @click="checkPhoto(item)">
          <!-- 相册操作 -->
          <div class="album-opreation">
            <el-dropdown @command="handleCommand">
              <i class="el-icon-more" style="color:#fff" />
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="'update' + JSON.stringify(item)">
                  <i class="el-icon-edit" />编辑
                </el-dropdown-item>
                <el-dropdown-item :command="'delete' + item.id">
                  <i class="el-icon-delete" />删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div class="album-photo-count">
            <div>{{ item.pictureTotal }}</div>
<!--            <i v-if="item.status == 2" class="iconfont el-icon-mymima" />-->
            <i class="iconfont el-icon-mymima" />
          </div>
          <el-image fit="cover" class="album-cover" :src="item.cover" />
          <div class="album-name">{{ item.name }}</div>
        </div>
      </el-col>
    </el-row>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="query.current"
      :page-sizes="[12, 24, 48]"
      :page-size="query.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="query.total">
    </el-pagination>
    <!-- 新增模态框 -->
    <el-dialog :visible.sync="addOrEdit" width="35%" top="10vh">
      <div class="dialog-title-container" slot="title" ref="albumTitle" />
      <el-form label-width="80px" size="medium" :model="albumForum">
        <el-form-item label="相册名称">
          <el-input style="width:220px" v-model="albumForum.name" />
        </el-form-item>
        <el-form-item label="相册描述">
          <el-input style="width:220px" v-model="albumForum.description" />
        </el-form-item>
        <el-form-item label="相册封面">
          <el-upload class="upload-demo" drag action="" :http-request="uploadMainImg">
            <img v-if="albumForum.cover" :src="albumForum.cover" width="360px" height="180px"/>
            <i v-else class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>
        <el-form-item label="相册容量">
          <el-input-number v-model="albumForum.size" @change="handleChange" :min="1" :max="500" label="相册容量"></el-input-number>
        </el-form-item>
        <el-form-item label="发布形式">
          <el-radio-group v-model="albumForum.isPublic">
            <el-radio :label="1">公开</el-radio>
            <el-radio :label="2">私密</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="closeSub">取 消</el-button>
        <el-button type="primary" @click="addOrEditAlbum">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</div>
</template>

<script>
import * as imageConversion from "image-conversion";
import albumApi from '../../api/album';
import fileApi from "@/api/file";
export default {
  created() {
    this.fetchAlbumList();
  },
  data: function() {
    return {
      keywords: "",
      loading: true,
      isdelete: false,
      addOrEdit: false,
      albumForum: {
        id: null,
        name: "",
        description: "",
        cover: "",
        isPublic: 1,
        size: 1
      },
      albumList: [],
      current: 1,
      size: 8,
      count: 0,
      query: {
        current: 1,
        size: 12,
        total: 0,
        name: ''
      },
      num: 1,
      type: '',
    };
  },
  methods: {
    // 获取相册列表
    async fetchAlbumList() {
      const {code, data} = await albumApi.albumList(this.query);
      if (code === 200) {
        this.albumList = data.albumRespVos;
        this.query.total = data.total;
      }
    },

    closeSub() {
      this.addOrEdit = false;
      this.albumForum.cover = '';
      this.albumForum.description = '';
      this.albumForum.size = '';
      this.albumForum.name = '';
      this.albumForum.isPublic = '';
    },

    // 重置
    reload() {
      this.query.name = '';
      this.query.current = 1;
      this.query.size = 12;
      this.fetchAlbumList();
    },

    // 上传相册封面图
    uploadMainImg(file) {
      const data = new FormData();
      data.append('file', file.file);
      fileApi.uploadImage(data).then(response => {
        if(response.code === 200) {
          this.albumForum.cover = response.data;
        } else if (response.code === 306) {
          this.$notify.error({
            title: '错误',
            message: '您没有上传文件权限，请联系管理员',
            duration: 1500
          });
        } else {
          this.$notify.error({
            title: '错误',
            message: '系统异常，请稍后再试',
            duration: 1500
          });
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: '上传失败'
        })
      })
    },

    handleChange(value) {
      // console.log(value);
    },

    openModel(item) {
      if (item) {
        this.albumForum = JSON.parse(item);
        this.$refs.albumTitle.innerHTML = "修改相册";
        this.type = 'update';
      } else {
        this.albumForum = {
          id: null,
          albumName: "",
          albumLabel: "",
          albumCover: "",
          status: 1
        };
        this.$refs.albumTitle.innerHTML = "新建相册";
        this.type = 'add';
      }
      this.addOrEdit = true;
    },
    checkPhoto(item) {
      // this.$router.push({ path: "/albums/" + item.id });
      this.$router.push({ path: "/picture/detail/" + item.id  });
    },

    checkDelete() {
      // this.$router.push({ path: "/photos/delete" });
    },

    addOrEditAlbum() {
      if (this.albumForum.name.trim() === "") {
        this.$message.error("相册名称不能为空");
        return false;
      }
      if (this.albumForum.description.trim() === "") {
        this.$message.error("相册描述不能为空");
        return false;
      }
      if (this.albumForum.cover === null) {
        this.$message.error("相册封面不能为空");
        return false;
      }
      // 新增相册
      if (this.type === 'add') {
        // const {code} = await albumApi.saveAlbum(this.albumForum);
        albumApi.saveAlbum(this.albumForum).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '新增成功',
              type: 'success',
              duration: 1500
            });
          } else if (response.code === 306) {
            this.$notify.error({
              title: '错误',
              message: '您没有权限，请联系管理员',
              duration: 1500
            });
          } else {
            this.$notify.error({
              title: '错误',
              message: '系统异常，请稍后再试',
              duration: 1500
            });
          }
          this.fetchAlbumList();
          this.addOrEdit = false;
          this.type = '';
        })
      } else if (this.type === 'update') {
        // const {code} = await albumApi.updateAlbum(this.albumForum);
        albumApi.updateAlbum(this.albumForum).then(response => {
          console.log("response.code", response.code)
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '编辑成功',
              type: 'success',
              duration: 1500
            });
          } else if (response.code === 306) {
            this.$notify.error({
              title: '错误',
              message: '您没有该权限，请联系管理员',
              duration: 1500
            });
          } else {
            this.$notify.error({
              title: '错误',
              message: '系统异常，请稍后再试',
              duration: 1500
            });
          }
          this.fetchAlbumList();
          this.addOrEdit = false;
          this.type = '';
        })
      }
    },

    // val 是切换之后的每页显示多少条
    handleSizeChange(val) {
      this.query.size = val;
      this.fetchAlbumList();
    },
    // 当页码改变后触发此方法 val是当前点击（或输入）的页码
    handleCurrentChange(val) {
      this.query.current = val;
      this.fetchAlbumList();
    },

    handleCommand(command) {
      const type = command.substring(0, 6);
      const data = command.substring(6);
      if (type === "delete") {
        this.albumForum.id = data;
        this.isdelete = true;
        this.deleteAlbum(data);
      } else {
        this.openModel(data);
      }
    },

    // 删除相册
    async deleteAlbum(id) {
      this.$confirm('确认删除这条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        albumApi.deleteAlbum(id).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1500
            });
          } else if (response.code === 306) {
            this.$notify.error({
              title: '错误',
              message: '您没有操作权限，请联系管理员',
              duration: 1500
            });
          } else {
            this.$notify.error({
              title: '错误',
              message: '系统异常，请稍后再试',
              duration: 1500
            });
          }
          // 刷新列表
          this.fetchAlbumList();
        })
      }).catch(() => {
        // 取消删除
      });
    },

    searchAlbums() {
      this.query.current = 1;
      this.fetchAlbumList();
    },
    sizeChange(size) {
      this.query.size = size;
      this.fetchAlbumList();
    },
    currentChange(current) {
      this.query.current = current;
      this.fetchAlbumList();
    }
  }
}
</script>

<style scoped>
.album-cover {
  position: relative;
  border-radius: 4px;
  width: 100%;
  height: 170px;
  margin-top: 10px;
}
.album-cover::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
}
.album-photo-count {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 1.5rem;
  z-index: 1000;
  position: absolute;
  left: 0;
  right: 0;
  padding: 0 0.5rem;
  bottom: 2.6rem;
  color: #fff;
}
.album-name {
  text-align: center;
  margin-top: 0.5rem;
}
.album-item {
  position: relative;
  cursor: pointer;
  margin-bottom: 1rem;
}
.album-opreation {
  position: absolute;
  z-index: 1000;
  top: 0.5rem;
  right: 0.8rem;
}
</style>
